package renguanyu.app.auth4fx.controller.user;

import javafx.concurrent.Task;
import renguanyu.app.auth4fx.App;
import renguanyu.app.auth4fx.model.user.UserDto;
import renguanyu.app.auth4fx.service.user.UserService;
import renguanyu.app.auth4fx.view.user.UserInfoSaveView;
import renguanyu.app.auth4fx.view.user.UserListView;

public class UserInfoSaveController extends Task<Void> {

    private UserInfoSaveView userInfoView;
    public UserInfoSaveController(UserInfoSaveView userInfoView) {
        this.userInfoView = userInfoView;
    }

    public void startAsyncSave() {
        System.out.println("UserInfoSave.execute");
        Thread thread = new Thread(this);
        thread.setDaemon(true);
        thread.start();
    }

    private Integer affectedRows = 0;
    @Override
    protected Void call() {
        System.out.println("UserInfoSave.call");
        UserDto userDto = buildUserDto();
        affectedRows = UserService.saveUser(userDto);
        return null;
    }

    private UserDto buildUserDto() {
        // 接收分数
        String name = userInfoView.nameProperty.get();
        String password = userInfoView.passwordProperty.get();
        // 封装DTO
        UserDto userDto = new UserDto();
        userDto.setName(name);
        userDto.setPassword(password);
        return userDto;
    }

    @Override
    protected void running() {
        System.out.println("UserInfoSave.running");
    }

    @Override
    protected void succeeded() {
        System.out.println("UserInfoSave.succeeded");
        if(affectedRows == 1){
            App.mainView.setCenter(new UserListView());
        }
    }

    @Override
    protected void failed() {
        System.out.println("UserInfoSave.failed");
    }
}
